const Base = require('./base.js');
const moment = require('moment');
//积分商城
module.exports = class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'gi.sort_order,gi.order_time desc';
        const goodsname = this.get('goodsname') || '';
        const category_id = this.get('category_id') || '';
        const state = this.get('state') || '';
        let seachdata = { 'hiolabs_goods.is_delete': 0, 'gi.id': ['!=', null] }, timesearch = {};
        if (category_id) {
            seachdata['hiolabs_goods.category_id'] = category_id;
        }
        if (goodsname) {
            seachdata['hiolabs_goods.name'] = ['like', `%${goodsname}%`];
        }
        if (state || state === 0) {
            seachdata['gi.is_delete'] = state;
        }

        const model = this.model('goods');
        const sp_model = this.model('goods_specification');
        const p_model = this.model('product');
        const bmodel = this.model('goods_integral');
        const data = await model.join({ table: 'goods_specification', join: 'right', as: 'gs', on: ['id', 'goods_id'] })
            .join({ table: 'product', join: 'right', as: 'gp', on: ['gs.id', 'goods_specification_ids'] })
            .join({ table: 'goods_integral', join: 'right', as: 'gi', on: ['gs.id', 'gi.spec_id'] })
            .where(
                seachdata
            ).field('hiolabs_goods.name,hiolabs_goods.https_pic_url,gs.value,gp.retail_price,gs.id as spec_id,gi.*')
            .order([sortField]).page(page, size).countSelect();
        //兑换值及剩余兑换值
        for (const item of data.data) {
            item.exchange_total = await this.model('order').join({ table: 'order_goods', join: 'right', as: 'og', on: ['id', 'order_id'] })
                .where({ 'og.is_delete': 0, 'hiolabs_order.order_type': ['in', [9, 10]], 'og.goods_id': item.goods_id, 'og.goods_specifition_ids': item.spec_id }).sum('og.number') - 0;
            item.exchange_limit = item.total - parseInt(item.exchange_total - 0);
        }
        return this.success(data);
    }

    async getSetsAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'hiolabs_goods.sort_order';
        const goodsname = this.get('goodsname') || '';
        const category_id = this.get('category_id') || '';
        let seachdata = { 'hiolabs_goods.is_delete': 0, 'gi.id': ['eq', null] }, timesearch = {};
        if (category_id || category_id === 0) {
            seachdata['hiolabs_goods.category_id'] = category_id;
        }
        if (goodsname) {
            seachdata['hiolabs_goods.name'] = ['like', `%${goodsname}%`];
        }

        const model = this.model('goods');
        const sp_model = this.model('goods_specification');
        const p_model = this.model('product');
        const bmodel = this.model('goods_integral');
        const data = await model.join({ table: 'goods_specification', join: 'right', as: 'gs', on: ['id', 'goods_id'] })
            .join({ table: 'product', join: 'left', as: 'gp', on: ['gs.id', 'goods_specification_ids'] })
            .join({ table: 'goods_integral', join: 'left', as: 'gi', on: ['gs.id', 'gi.spec_id'] })
            .where(
                seachdata
            ).field('hiolabs_goods.name,hiolabs_goods.https_pic_url,gs.value,gp.retail_price,gs.id as spec_id')
            .order([sortField]).page(page, size).countSelect();
        return this.success(data);
    }

    async saveAction() {
        const model = this.model('goods_integral');
        const g_model = this.model('goods_specification');
        const values = this.post();
        let id = this.post('id');
        const spec_id = this.post('spec_id');
        if (!spec_id) {
            return this.fail('缺少参数规格spec_id');
        }
        const goods = await g_model.where({ id: spec_id }).find();
        values['goods_id'] = goods.goods_id;
        if (id > 0) {
            id = await model.where({ id: id }).update(values);
        } else {
            values['id'] = 0;
            id = await model.add(values);
            values['id'] = id;
        }
        return this.success(values);
    }
    async updateAction() {
        const model = this.model('goods_integral');
        const values = this.post();
        const id = this.post('id');
        let data = await model.where({ id: id }).update(values);
        return this.success(data);
    }

    async readAction() {
        const model = this.model('goods');
        const id = this.get('id');
        const data = await model.join({ table: 'goods_specification', join: 'right', as: 'gs', on: ['id', 'goods_id'] })
            .join({ table: 'product', join: 'right', as: 'gp', on: ['gs.id', 'goods_specification_ids'] })
            .join({ table: 'goods_integral', join: 'right', as: 'gi', on: ['gs.id', 'gi.spec_id'] })
            .where(
                { 'gi.id': id }
            ).field('hiolabs_goods.name,hiolabs_goods.https_pic_url,gs.value,gp.retail_price,gs.id as spec_id,gi.*').find();
        return this.success(data);
    }
    /**
    * TODO商品有效期定时上下架
    */
    async activeAction() {
        const model = this.model('goods_integral');
        const values = this.post();
        const id = this.post('id');
        values['is_delete'] = 0;
        let data = await model.where({ id: id }).update(values);
        return this.success(data);
    }
    /**
     * 置顶及取消置顶
     */
    async topAction() {
        const model = this.model('goods_integral');
        const values = this.post();
        const id = this.post('id');
        const sort_order = this.post('sort_order');
        let data;

        try {
            await model.startTrans();
            data = await model.where({ id: id }).update({ sort_order: sort_order });
            await model.where({ id: ['!=', id] }).update({ sort_order: 1 - sort_order });
            await model.commit();
        } catch (e) {
            await model.rollback();
            return this.fail('事务，未知错误');
        }
        return this.success(data);
    }

    /**
    * 置顶及取消置顶
    */
    async orderAction() {
        const model = this.model('goods_integral');
        const values = this.post();
        const id = this.post('id');
        const sort_order = this.post('sort_order');
        let data;

        if (sort_order == 0) {
            data = await model.where({ id: id }).update({ sort_order: 0, order_time: parseInt(new Date().getTime() / 1000) });
        } else {
            data = await model.where({ id: id }).update({ sort_order: 1, order_time: 0 });

        }
        return this.success(data);
    }


    async deleteAction() {
        const model = this.model('goods_integral');
        const id = this.post('id');
        let data = await model.where({ id: id }).delete();
        return this.success(data);
    }

    async getCategoryAction() {
        const model = this.model('category');
        const data = await model.field('id as category_id,name,parent_id').order(['sort_order ASC']).select();
        const topCategory = data.filter((item) => {
            return item.parent_id === 0;
        });
        const categoryList = [{ category_id: 0, name: '全部', parent_id: 0, level: 0 }];
        topCategory.map((item) => {
            item.level = 1;
            categoryList.push(item);
            data.map((child) => {
                if (child.parent_id === item.category_id) {
                    child.level = 2;
                    categoryList.push(child);
                }
            });
        });
        return this.success(categoryList);
    }

    /**
     * 兑换统计
     */
    async exchangeStaticAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'og.id';
        const goodsname = this.get('goodsname') || '';
        const category_id = this.get('category_id') || 0;
        const spec_id = this.get('spec_id') || 0;
        const begin = this.get('begin') || '';
        const end = this.get('end') || '';
        const status = this.get('status') || '';
        let name = this.get('name') || '';
        const buffer = Buffer.from(name);
        let nickname = buffer.toString('base64');

        let searchData = { 'hiolabs_order_goods.is_delete': 0, 'og.order_type': ['in', [9, 10]] }, timesearch = {};
        if (category_id) {
            searchData['og.category_id'] = category_id;
        }
        if (spec_id) {
            searchData['hiolabs_order_goods.goods_specifition_ids'] = spec_id;
        }
        if (goodsname) {
            searchData['hiolabs_order_goods.name'] = ['like', `%${goodsname}%`];
        }
        if (status) {
            searchData['og.order_status'] = status;
        }

        if (name) {
            searchData['_complex'] = {
                'ou.nickname': ['like', `%${nickname}%`],
                'ou.name': ['like', `%${name}%`],
                'ou.mobile': ['like', `%${name}%`],
                _logic: 'or'
            };
        }
        if (begin || end) {
            if (begin) {
                timesearch['egt'] = parseInt(new Date(begin).getTime() / 1000);
            }
            if (end) {
                timesearch['elt'] = parseInt(new Date(end).getTime() / 1000);
            }
            searchData['og.add_time'] = timesearch;
        }


        const model = this.model('order_goods');
        const data = await model.join({ table: 'order', join: 'left', as: 'og', on: ['order_id', 'id'] })
            .join({ table: 'user', join: 'left', as: 'ou', on: ['user_id', 'id'] }).where(searchData)
            .field('hiolabs_order_goods.*,og.order_sn,og.add_time,og.order_type,og.province,og.city,og.district,og.order_status,ou.nickname,ou.name,ou.mobile')
            .order(sortField).page(page, size).countSelect();
        for (const item of data.data) {
            item.nickname = Buffer.from(item.nickname, 'base64').toString();
            item.cost = item.number * item.retail_price;
            item.orderstatus = await this.model('order').getOrderStatusByStatus(item.order_status);//交易状态
            item.order_time = moment.unix(item.add_time).format('YYYY-MM-DD');
            //地址
            if (item.order_type == 9) {
                let province_name = await this.model('region').getRegionName(item.province);
                let city_name = await this.model('region').getRegionName(item.city);
                let district_name = await this.model('region').getRegionName(item.district);
                item.full_region = province_name + city_name + district_name;
                item.send_type = '包邮';
            } else {
                item.full_region = '';
                item.send_type = '自提';
            }
        }

        return this.success(data);
    }

    /*
     * 积分统计
     */
    async integralStaticAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'integral';
        let nickname = this.get('nickname') || '';
        const buffer = Buffer.from(nickname);
        let name = this.get('name') || '';
        let mobile = this.get('mobel') || '';
        let tag_ids = this.get('tag_ids') || [];
        let seachdata = {integral:['>',0]};

        if (name) {
            nickname = buffer.toString('base64');
            seachdata.name = ['like', `%${name}%`];
        }
        if (nickname) {
            seachdata.nickname = ['like', `%${nickname}%`];
        }
        if (mobile) {
            seachdata.mobile = ['like', `%${mobile}%`];
        }
        if (tag_ids && tag_ids.length > 0) {
            let uids = await this.model('user_tag').where({ tag_id: ['in', tag_ids] }).getField('user_id');
            seachdata.id = ['in', uids];
        }

        const model = this.model('user');
        const data = await model.where(seachdata).order('integral DESC').page(page, size).countSelect();

        const i_total = await this.model('task_integral').where({task_id:['>',0]}).sum('integral');
        const u_total = await model.where(seachdata).sum('integral');
        const u_count =  await model.where({integral:['>',0]}).count('id');
        for(const item of data.data){
            item.integralremain=item.integral-item.f_integral;//可用权益数
        }

        return this.success({
            integraltotal:i_total,
            userintegtal:u_total,
            usernum:u_count,
            data:data
        });
    }


    /**
     * 交易统计
     */
    async applyStaticAction() {
        const model = this.model('task_integral');
        let searchData={ 'hu.nickname': ['!=', null]},timesearch = {};
        // let sql = 'hiolabs_task_integral.task_id>0 and hu.nickname is not null ';
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const shelves_beg = this.get('begin') || '';
        const shelves_end = this.get('end') || '';
        const apply = this.get('applymobile') || '';
        const accept = this.get('acceptmobile') || '';

        if (shelves_beg || shelves_end) {
            if (shelves_beg) {
                timesearch['egt'] = shelves_beg;
            }
            if (shelves_end) {
                // timesearch['elt'] = shelves_end;
                timesearch['elt'] = moment(shelves_end).add(1, "day").format("YYYY-MM-DD");
                // sql+= ' and hiolabs_task_integral.create_time<='+shelves_end;
            }
            searchData['hiolabs_task_integral.create_time'] = timesearch;
        }
        let applytotal = 0 ;//交易总数
        let applynumber = 0;//交易次数

        if(apply&&accept){
            searchData['_complex'] = {
                // _complex:{'hu.mobile':['like',`%${apply}%`],'hiolabs_task_integral.integral':['lt',0],_logic: 'AND'}, 
                // _complex:{'su.mobile':['like',`%${accept}%`],'hiolabs_task_integral.integral':['egt',0],_logic: 'AND'}, 
                'hu.mobile':['like',`%${apply}%`],
                'su.mobile':['like',`%${accept}%`],
                _logic: 'AND' 
            };

        }else if(apply){
            searchData['hu.mobile']=['like',`%${apply}%`];
            searchData['hiolabs_task_integral.integral']=['<',0];

        }else if(accept){
            searchData['hu.mobile']=['like',`%${accept}%`];
            searchData['hiolabs_task_integral.integral']=['egt',0];
        }


        let data = await model.join({ table: 'user',  join: 'left',as:'hu', on: ['user_id', 'id'] })
        .join({ table: 'user',  join: 'left',as:'su', on: ['user_id', 'id'] })
        .where(searchData).order('hiolabs_task_integral.create_time').field("hiolabs_task_integral.*,hu.id as uid,hu.nickname,hu.mobile").page(page,size).countSelect();
        for (const item of data.data) {
            item.nickname = Buffer.from(item.nickname, 'base64').toString();
            if(item.integral<0){
                item.integral=item.integral*-1;
                item.apply=item.nickname +'/'+item.mobile;
                item.accept='商城';
            }else{
                item.apply='商城';
                item.accept=item.nickname +'/'+item.mobile;
            }
            
        }
        let idata = await model.join({ table: 'user',  join: 'left',as:'hu', on: ['user_id', 'id'] })
        .join({ table: 'user',  join: 'left',as:'su', on: ['user_id', 'id'] })
        .where(searchData).order('hiolabs_task_integral.create_time').getField("hiolabs_task_integral.integral");
        for(const ig of idata){
            ig<0?applytotal-=ig:applytotal+=ig;
        }
        return this.success({
            applytotal:applytotal,
            applynumber:data.count,
            data:data
        });
    }

    /**
     * 权益发行
     */
    async integralPublicAction() {//发行
        let values = this.post();
        const model = this.model('setmodel');
        const data = await model.where({setmodel:'integralPublic'}).find(); //从数据库中将配置读取出来，然后设置
        let newdata={
            setmodel:'integralPublic',
            setting:JSON.stringify(values),
            user_id:think.userId,
            update_time:Math.floor(new Date().getTime()/1000)
        }
        if(think.isEmpty(data)){
            await model.add(newdata);
        }else{
            await model.where({setmodel:'integralPublic'}).update(newdata);
        }

        return this.success(values);
    }
    async getIntegralPublicAction() {//获取
        const model = this.model('setmodel');
        const data = await model.where({setmodel:'integralPublic'}).find(); //从数据库中将配置读取出来，然后设置
        let r;
        if(think.isEmpty(data)){
            r={};
        }else{
            r=JSON.parse(data.setting);
        }

        return this.success(r);
    }

    async deductionAction() {//权益抵扣设置
        let values = this.post();
        const model = this.model('setmodel');
        const data = await model.where({setmodel:'deduction'}).find(); //从数据库中将配置读取出来，然后设置
        let newdata={
            setmodel:'deduction',
            setting:JSON.stringify(values),
            user_id:think.userId,
            update_time:Math.floor(new Date().getTime()/1000)
        }
        if(think.isEmpty(data)){
            await model.add(newdata);
        }else{
            await model.where({setmodel:'deduction'}).update(newdata);
        }

        return this.success(values);
    }
    async getDeductionAction() {//设置
        const model = this.model('setmodel');
        const data = await model.where({setmodel:'deduction'}).find(); //从数据库中将配置读取出来，然后设置
        let r;
        if(think.isEmpty(data)){
            r={};
        }else{
            r=JSON.parse(data.setting);
        }

        return this.success(r);
    }

    /**
     * 线上订单抵扣统计
     */
    async onlineOffsetAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const shelves_beg = this.get('begin') || '';
        const shelves_end = this.get('end') || '';
        let nickname = this.post('nickname') || '';
        const buffer = Buffer.from(nickname);
        let name = this.post('name') || '';
        let mobile = this.post('mobile') || '';
        let searchData={ 'ou.nickname': ['!=', null]},timesearch = {};

        if (shelves_beg || shelves_end) {
            if (shelves_beg) {
                timesearch['egt'] = Math.floor(moment(shelves_beg).valueOf()/1000);
            }
            if (shelves_end) {
                // timesearch['elt'] = shelves_end;
                timesearch['lt'] = Math.floor(moment(shelves_end).add(1, "day").valueOf()/1000);
                // sql+= ' and hiolabs_task_integral.create_time<='+shelves_end;
            }
            searchData['hiolabs_order_offset.add_time'] = timesearch;
        }
        if (name) {
            seachdata['ou.name'] = ['like', `%${name}%`];
        }
        if (nickname) {
            nickname = buffer.toString('base64');
            seachdata['ou.nickname'] = ['like', `%${nickname}%`];
        }
        if(mobile){
            seachdata['ou.mobile'] = ['like', `%${mobile}%`];
        }


        const model = this.model('order_offset');
        const data = await model.join({ table: 'order', join: 'left', as: 'og', on: ['order_id', 'id'] })
            .join({ table: 'order_goods', join: 'left', as: 'oog', on: ['order_id', 'order_id'] })
            .join({ table: 'user', join: 'left', as: 'ou', on: ['user_id', 'id'] }).where(searchData)
            .field('hiolabs_order_offset.*,og.order_sn,ogg.add_time as order_time,og.order_type,og.order_status,ou.nickname,ou.name,ou.mobile')
            .order('ogg.add_time').page(page, size).countSelect();
        for (const item of data.data) {
            item.nickname = Buffer.from(item.nickname, 'base64').toString();
            item.orderstatus = await this.model('order').getOrderStatusByStatus(item.order_status);//交易状态
            item.order_time = moment.unix(item.order_time).format('YYYY-MM-DD HH:mm:ss');
            item.offset_time = moment.unix(item.add_time).format('YYYY-MM-DD HH:mm:ss');
            //地址
            // if (item.order_type == 9) {
            //     let province_name = await this.model('region').getRegionName(item.province);
            //     let city_name = await this.model('region').getRegionName(item.city);
            //     let district_name = await this.model('region').getRegionName(item.district);
            //     item.full_region = province_name + city_name + district_name;
            //     item.send_type = '包邮';
            // } else {
            //     item.full_region = '';
            //     item.send_type = '自提';
            // }
        }
        return this.success(data);
    }

    /**
     * 线下门店抵扣统计
     */
    async offlineOffsetAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const shelves_beg = this.get('begin') || '';
        const shelves_end = this.get('end') || '';
        const store_id = this.get('store_id') || 0;
        
        let name = this.post('name') || '';
        let mobile = this.post('mobile') || '';
        // let nickname = this.post('nickname') || '';
        let searchData={ 'ou.nickname': ['!=', null]},timesearch = {};
        const buffer = Buffer.from(name);
        if(store_id){
            searchData['hs.id'] = store_id;
        }

        if (shelves_beg || shelves_end) {
            if (shelves_beg) {
                timesearch['egt'] = Math.floor(moment(shelves_beg).valueOf()/1000);
            }
            if (shelves_end) {
                timesearch['lt'] = Math.floor(moment(shelves_end).add(1, "day").valueOf()/1000);
            }
            searchData['hiolabs_store_offset.add_time'] = timesearch;
        }
        // if (name) {
        //     seachdata['ou.name'] = ['like', `%${name}%`];
        // }
        // if (nickname) {
        //     nickname = buffer.toString('base64');
        //     seachdata['ou.nickname'] = ['like', `%${nickname}%`];
        // }
        // if(mobile){
        //     seachdata['ou.mobile'] = ['like', `%${mobile}%`];
        // }

        if(name){
             let nickname = buffer.toString('base64');
            searchData['_complex'] = {
                'ou.nickname':['like', `%${nickname}%`],
                'ou.name':['like', `%${name}%`],
                'ou.mobile':['like', `%${name}%`],
                _logic:'or'
            };
        }


        const model = this.model('store_offset');
        const total = await model.join({ table: 'user', join: 'left', as: 'ou', on: ['user_id', 'id'] }).sum('input_offset');
        const number = await model.join({ table: 'user', join: 'left', as: 'ou', on: ['user_id', 'id'] }).count('hiolabs_store_offset.id');
        const usernum = await model.join({ table: 'user', join: 'left', as: 'ou', on: ['user_id', 'id'] }).count('distinct ou.id');
        const data = await model
            .join({ table: 'store', join: 'left', as: 'hs', on: ['store_id', 'id'] })
            .join({ table: 'user', join: 'left', as: 'ou', on: ['user_id', 'id'] }).where(searchData)
            .field('hiolabs_store_offset.*,hs.name as storename,ou.nickname,ou.name,ou.mobile')
            .order('ogg.add_time').page(page, size).countSelect();
        for (const item of data.data) {
            item.nickname = Buffer.from(item.nickname, 'base64').toString();
            item.orderstatus = await this.model('order').getOrderStatusByStatus(item.order_status);//交易状态
            item.offset_time = moment.unix(item.add_time).format('YYYY-MM-DD HH:mm:ss');
            //地址
            // if (item.order_type == 9) {
            //     let province_name = await this.model('region').getRegionName(item.province);
            //     let city_name = await this.model('region').getRegionName(item.city);
            //     let district_name = await this.model('region').getRegionName(item.district);
            //     item.full_region = province_name + city_name + district_name;
            //     item.send_type = '包邮';
            // } else {
            //     item.full_region = '';
            //     item.send_type = '自提';
            // }
        }
        return this.success({
            total:total,number:number,usernum:usernum,
            listdata:data
        });
    }



};